﻿using Adnc.Shared.RpcServices.Services;
using Autofac;
using Hangfire;
using MoBaoPay;
using WYT.Pay.Application.EventSubscribers;

namespace WYT.Pay.WebApi
{
    public class Startup
    {
        private readonly IHostEnvironment _environment;

        private IServiceCollection _services;

        private IConfiguration _config;

        public Startup(IHostEnvironment environment, IConfiguration config)
        {
            _environment = environment;
            _config = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            _services = services;
            services.AddWYTServices(registion => {
                var policies = registion.GenerateDefaultRefitPolicies();
#if DEBUG
                registion.AddRpcService<IUserRpcService>("https://gateway.wyuntao.com", policies);
                registion.AddRpcService<IOrdersRpcService>("https://gateway.wyuntao.com", policies);
                registion.AddEventBusSubscribers();
#else
                registion.AddRpcService<IUserRpcService>("wyt.usr.webapi", policies);
                registion.AddRpcService<IOrdersRpcService>("wyt.ord.webapi", policies);
                registion.AddEventBusSubscribers<CapEventSubscriber>();
#endif

                registion.AddHangfire();
            });
            services.AddMoBaoPay();
            services.Configure<MoBaoOptions>(_config.GetSection("MoBaoOptions"));
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterAdncModules(_services);
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseAdncMiddlewares();

            #region 定时任务
            RecurringJob.AddOrUpdate<HangfireJobService>(x => x.PaymentOrderTimeoutCheck(), Cron.Minutely(), TimeZoneInfo.Local);
            #endregion
            if (_environment.IsProduction() || _environment.IsStaging())
            {
                app.RegisterToConsul();
            }
        }
    }
}
